<?php

/**
 * Site snippet displaying widget
 */
class SiteSnippetWidget extends CWidget
{
	/**
	 * @var string Widget title
	 */
	public $title = '';
	
	/**
	 * @var string Snippet id. Max length is 255 symbols.
	 */
	public $snippetId = '';
	
	/**
	 * @var string Text appended before widget
	 */
	public $before = '';
	
	/**
	 * @var string Text appended after widget
	 */
	public $after = '';
	
	private $_model = null;
	private $_cache = null;
	
	/**
	 * Init method
	 */
	public function init()
	{
		if(empty($this->snippetId))
		{
			throw new CException("Snippet id can't be empty!");
		}
		
		$this->_cache = Yii::app()->{Yii::app()->getModule('sitesnippet')->cacheId};
	}
	
	/**
	 * Display widget
	 */
	public function run()
	{
		$this->render('sitesnippet', array(
			'snippetId' => $this->snippetId,
			'title' => $this->title,
		));
	}
	
	protected function getModel()
	{
		if($this->_model == null)
		{
			$this->_model = $this->_cache->get('sitesnippet_'.$this->snippetId);
			
			if($this->_model == null)
			{
				$this->_model = SiteSnippet::model()->findByPk($this->snippetId);
				if($this->_model == null)
				{
					$this->_model = new SiteSnippet;
					$this->_model->id = $this->snippetId;
					$this->_model->save();
				}
				
				$this->_cache->set('sitesnippet_'.$this->snippetId, $this->_model);
			}
		}
		
		return $this->_model;
	}
}